import { Ref } from 'vue'

const useAnimate = (ele: Ref<HTMLElement>, emit: any) => {
  const data = {
    aid: 0,
    t: 0,
    b: 0,
    c: 0,
    d: 1
  }

  const runAnimate = (time: number) => {
    firstTime = firstTime === 0 ? time : firstTime
    data.t = time - firstTime
    if (timeGap === 0) {
      timeGap = time
    } else {
      timeGap = time - timeGap
      data.b += easeInOut(data.t / 1000, data.b, data.c, data.d) / (1000 / timeGap)
      timeGap = time
    }
    if (ele) {
      (ele.value as HTMLElement).scrollTop -= data.b
    }
    if (data.t < data.d * 1000) {
      data.aid = requestAnimationFrame(runAnimate)
    } else {
      cancelAnimationFrame(data.aid)
      data.aid = 0
      data.t = 0
      data.b = 0
      data.c = 0
      data.d = 1
      firstTime = 0
      timeGap = 0
      emit('complete')
    }
  }

  let firstTime = 0, timeGap = 0
  
  const easeInOut = function(t: number, b: number, c: number, d: number){
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * (( t)*(t-2) - 1) + b;
  }

  const handleBackTop = () => {
    data.c = (ele.value as HTMLElement).scrollTop || 0
    requestAnimationFrame(runAnimate)
  }

  return {
    handleBackTop
  }
}

export default useAnimate